package com.ray.test.actuator.params;

import com.ray.test.mock.MockConfig;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author bo shen
 * @Description: 参数构造
 * @Class: ParamsBuilder
 * @Package com.ray.test.actuator.params
 * @date 2019/12/12 14:26
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class ParamsBuilder implements Bulider<Parameter[], List<Object>> {

    private static ParamsBuilder instance = new ParamsBuilder();

    public static ParamsBuilder getInstance() {
        return instance;
    }

    @Override
    public List<Object> bulider(Parameter[] parameters, Method method, Parameter parameter1) {
        //参数列表
        List<Object> params = new ArrayList<>();
        for (Parameter parameter : parameters) {
            //全局配置
            Object gp = getGlobeConfigValue(parameter, method);
            //获取方法是否配置参数
            Object p = getConfigValue(parameter, method);
            if (p == null && gp == null) {
                log.info("构建参数:{},类型:{}", parameter.getName(), parameter.getType());
                params.add(ParamsInitBuilder.getInstance().bulider(parameter.getType(), method, parameter));
            } else {
                if (p == null) {
                    params.add(gp);
                } else {
                    params.add(p);
                }
            }
        }
        return params;
    }

    private Object getGlobeConfigValue(Parameter parameter, Method method) {
        return MockConfig.getParams().get().get(parameter.getType());
    }

    private Object getConfigValue(Parameter parameter, Method method) {
        if (method == null) return null;
        Map<String, Object> paramsMap = MockConfig.getMethodParams().get().get(method.getName());
        if (paramsMap != null) {
            log.info("参数名称:{}", parameter.getName());
            return paramsMap.get(parameter.getName());
        }
        return null;
    }


}
